package edu.bw.web.role;

import cn.hutool.json.JSONUtil;
import edu.bw.common.CommonResult;
import edu.bw.dto.InsertRoleForm;
import edu.bw.service.RoleService;
import edu.bw.service.impl.RoleServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/role/insert")
public class InsertRoleServlet extends HttpServlet {

    RoleService roleService = new RoleServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      //{"id":0,"roleName":"测试01","permissions":[5,6,7,8],"desc":"测试01","changed":true}
      //1.解析前端的数据
        String reqJSON = request.getReader().readLine();
        InsertRoleForm insertRoleForm = JSONUtil.toBean(reqJSON, InsertRoleForm.class);

        //2.调用RoleService处理相关逻辑
        Integer rows = roleService.insert(insertRoleForm);

        //3.将rows写给前端
        response.getWriter().write(JSONUtil.toJsonStr(CommonResult.ok().put("rows", rows)));
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}